const router = require('koa-router')();
const controller = require('../controller/user')
const userModel = require('../models/user')
const auth = require('../util/auth')
const tool = require('../util/tool')
const tokenHelper = require('../util/token-helper')
const ApiErrorNames = require('../error/api_error_name');


//查
router.get('/',auth.isAdmin, controller.find);
// 查 动态路由
router.get('/:id', controller.detail);

// 增
router.post('/', auth.isAdmin, controller.add);

//修改密码
router.post('/changepw', async (ctx) => {

  const data = ctx.request.body;
  //const token = tool.getTokenFromCtx(ctx);
  const user = tokenHelper.decodeToken(ctx);
  //管理员或是自己本身
  if (user.userId == data.userId || user.rank < 2) {
    await userModel.findOne({_id: data.userId, password: data.oldPassword}).exec().then(
      async res => {
        if (res) {
          await userModel.findOneAndUpdate({_id: data.userId}, {
              password: data.newPassword,
            },
            {
              new: true, // 返回修改后的数据
            }).exec().then((res) => {
              if (res) {
                ctx.body = res;
              } else {
                throw new ApiError(ApiErrorNames.UNKNOW_ERROR);
              }
            }
          );
        } else {
          ctx.body = "error"
        }
      }
    )
  } else {
    ctx.status = 403
    throw new ApiError(ApiErrorNames.NO_AUTH);
  }

  // ctx.body = {userId:user.userId,userName:user.userName,token:newToken};
});

// 改
router.put('/:id',auth.isAdmin, controller.update);

// 删
router.del('/:id', auth.isAdmin, controller.delete);


module.exports = router;
